package com.itheima.reggie.web.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//管理端菜品模块的表现层控制器
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    //分页查询
    @GetMapping("/page")
    public ResultInfo findByPage(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                 String name) {
        //调用service查询
        Page<Dish> page = dishService.findByPage(pageNum, pageSize, name);
        //返回结果
        return ResultInfo.success(page);
    }

    //新增菜品
    @PostMapping
    public ResultInfo save(@RequestBody Dish dish) {
        //调用service
        dishService.save(dish);
        //返回
        return ResultInfo.success();
    }

    //修改菜品之回显菜品
    @GetMapping("/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        //调用service
        Dish dish = dishService.findById(id);
        //返回
        return ResultInfo.success(dish);
    }

    //修改菜品
    @PutMapping
    public ResultInfo update(@RequestBody Dish dish) {
        //调用service
        dishService.update(dish);
        //返回
        return ResultInfo.success();
    }

    //停售菜品
    @PostMapping("/status/{status}")
    public ResultInfo stopBuy(@PathVariable Integer status,@RequestParam List<Long> ids) {
        //调用service
        dishService.stopBuy(status, ids);
        //返回
        return ResultInfo.success();
    }

    //删除菜品
    @DeleteMapping
    public ResultInfo delete(@RequestParam List<Long> ids) {
        //调用service
        String noDeleteName = dishService.delete(ids);
        //判断名字是否为空
        if (noDeleteName != "") {
            return ResultInfo.error(noDeleteName.substring(0, noDeleteName.length() - 1) + "在售,不能删除!");
        }
        //返回
        return ResultInfo.success();
    }

    //新增套餐之回显菜品
    @GetMapping("/list")
    public ResultInfo findList(Long categoryId,String name) {
        //调用service
        List<Dish> dishList = dishService.findList(categoryId,name);
        //返回
        return ResultInfo.success(dishList);
    }
}